package com.lqz.realm;

import java.util.ArrayList;
import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import com.lqz.model.ActiveUser;
import com.lqz.model.SysUser;
import com.lqz.service.UserService;

public class DataSourceRealm extends AuthorizingRealm {

	@Autowired
	private UserService userService;

	@Override
	public void setName(String name) {
		super.setName("DataSourceRealm");
	}

	// 用于认证
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		// TODO Auto-generated method stub

		// token是用户输入的用户名和密码
		// 第一步从token中取出用户名
		String userCode = (String) token.getPrincipal();

		// 第二步：根据用户输入的userCode从数据库查询
		SysUser sysUser = null;
		try {
			sysUser = userService.findSysUserByUserCode(userCode);
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		// 如果查询不到返回null
		if (sysUser == null) {//
			throw new UnknownAccountException("用户不存在");
		}
		// 根据用户的信息进行反馈，则抛出LockedAccountException异常。
		if (!"1".equals(sysUser.getUserStatus())) {
			throw new LockedAccountException("用户被锁定");
		}
		// 从数据库查询到密码
		String password = sysUser.getPassword();

		// 盐
		String salt = sysUser.getSalt();

		// 如果查询到返回认证信息AuthenticationInfo

		// activeUser就是用户身份信息
		ActiveUser activeUser = new ActiveUser();

		activeUser.setUserid(sysUser.getUserId());
		activeUser.setUsercode(sysUser.getUserCode());
		activeUser.setUsername(sysUser.getUserName());

		// 根据用户id取出菜单
		List<?> menus = null;
		try {
			// 通过service取出菜单
			menus = userService.findMenuListByUserId(sysUser.getUserId());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// 将用户菜单 设置到activeUser
		activeUser.setMenus(menus);

		// 将activeUser设置simpleAuthenticationInfo
		SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(activeUser, password,
				ByteSource.Util.bytes(salt.getBytes()), this.getName());
		System.out.println(simpleAuthenticationInfo.getPrincipals().getPrimaryPrincipal());
		// System.out.println(simpleAuthenticationInfo.toString());
		return simpleAuthenticationInfo;
	}

	// 用于授权
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		// TODO Auto-generated method stub
		System.out.println();
		System.out.println();
		System.out.println("-----------用户查询数据库获取权限----------");
		// 获取主身份信息
		ActiveUser activeUser = (ActiveUser) principals.getPrimaryPrincipal();
		// 根据身份信息获取权限信息
		List<String> perms = null;
		try {
			perms = userService.findPermissionListByUserId(activeUser.getUsercode());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		List<String> p = new ArrayList<String>();
		if (perms != null) {
			for (String s : perms) {
				p.add(s);
			}
		}
		SimpleAuthorizationInfo s = new SimpleAuthorizationInfo();
		s.addStringPermissions(p);
		return s;
	}

	// 用于清空缓存
	public void clearCached() {
		PrincipalCollection principals = SecurityUtils.getSubject().getPrincipals();
		super.clearCache(principals);
	}

}
